<template>
   <el-button type="success" @click="open(null)">新增</el-button>
    <el-card >
        
        <el-table :data="OrderForm" style="width: 100%">
    <el-table-column prop="orderFormId" label="订单单号" width="170" />
    <el-table-column prop="itemId" label="商品编号" width="150" />
    <el-table-column prop="itemNum" label="数量" width="120" />
    <el-table-column prop="amount" label="总金额" width="140" />
    <el-table-column prop="type" label="出入库类型" width="150">
      <template #default="scope">
        <span>{{ scope.row.type == '1' ? '入库' : scope.row.type == '2' ? '出库' : scope.row.type }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" width="130">
      <template #default="scope">
        <span>{{ formatDate(scope.row.createTime) }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="userId" label="进货人" width="130" />
    <el-table-column prop="remark" label="备注" width="150" />
    <el-table-column label="操作" width="160">
      <template #default="scope">
        <el-button 
          type="primary" 
          size="small" 
          @click="open(scope.row)"
        >
          修改
        </el-button>
        <el-button 
          type="danger" 
          size="small" 
          @click="Del(scope.row.id)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页组件 -->
  <div style="margin-top: 20px; text-align: right;">
    <el-pagination
      v-model:current-page="model.pageindex"
      v-model:page-size="model.pagesize"
      :page-sizes="[5, 10, 20, 50]"
      :total="model.totalCount"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

    </el-card>
 
     <el-dialog :title="cnm.title" v-model="cnm.isopen" width="600px">
    <el-form
      ref="orderForm"
      :model="form"
      label-width="120px"
      style="width: 100%"
    >
      <!-- 订单单号 -->
      <el-form-item label="订单单号">
        <el-input v-model="form.orderFormId" placeholder="订单编号系统自动生成" readonly disabled />
      </el-form-item>

      <!-- 商品编号（下拉框） -->
      <el-form-item label="商品编号">
        <el-select
          v-model="form.itemId"
          placeholder="请选择商品编号"
          style="width: 100%"
        >
          <el-option
            v-for="item in Dm_Item"
            :key="item.itemid"
            :label="item.itemname"
            :value="item.itemid"
          />
        </el-select>
      </el-form-item>

      <!-- 数量 -->
      <el-form-item label="数量">
        <el-input-number v-model="form.itemNum" :min="1" />
      </el-form-item>

      <!-- 总金额 -->
      <el-form-item label="总金额">
        <el-input v-model="form.amount" placeholder="请输入总金额" />
      </el-form-item>

      <!-- 出入库类型（单选框） -->
      <el-form-item label="出入库类型">
        <el-radio-group v-model="form.type">
          <el-radio :value="1">入库</el-radio>
          <el-radio :value="2">出库</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 创建时间 -->
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="form.createTime"
          type="datetime"
          placeholder="选择创建时间"
        />
      </el-form-item>

      <!-- 供应商编号（下拉框） -->
        <el-form-item label="供应商编号">
    <el-select
      v-model="form.entId"
      placeholder="请选择供应商编号"
      style="width: 100%"
    >
      <el-option
        v-for="item in Dm_Ent"
        :key="item.entid"
        :label="item.entname"
        :value="item.entid"
      />
    </el-select>
  </el-form-item>

      <!-- 进货人ID -->
      <el-form-item label="进货人">
        <el-input v-model="form.userId" placeholder="请输入进货人" />
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注">
        <el-input
          type="textarea"
          v-model="form.remark"
          placeholder="请输入备注信息"
        />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>


</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton, ElTable, ElTableColumn, ElPagination } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { fr } from 'element-plus/es/locales.mjs'

const OrderForm=ref([{
  id:"",
 orderFormId: '',
  itemId: '',      
  itemNum: 0,
  amount: '',
  type: '0', // 出入库类型（1:入库, 2:出库）
  createTime: '',
  entId: '',       
  userId: '',
  remark: ''
}])

// 控制弹窗显示
const dialogVisible = ref(false)

// 表单数据
const form = reactive({
  orderFormId: '',
  itemId: '', // 商品编号（下拉框绑定值）
  itemNum: 0,
  amount: '',
  type: 0, // 出入库类型（单选框绑定值）
  createTime: '',
  entId: '', // 供应商编号（下拉框绑定值）
  userId: '',
  remark: ''
})
const updateform = reactive({
  id:'',
  orderFormId: '',
  itemId: '', // 商品编号（下拉框绑定值）
  itemNum: 0,
  amount: '',
  type: 0, // 出入库类型（单选框绑定值）
  createTime: '',
  entId: '', // 供应商编号（下拉框绑定值）
  userId: '',
  remark: ''
})
const model=ref({
  pageindex: 1,
  pagesize: 5,       // 商品编号（下拉框绑定值）
  totalCount: 0,
  totalPages: 0
})


const Dm_Ent=ref([{
    entid:"",
    entname:""
}])
const Dm_Item=ref([{
    itemid:"",
    itemname:""
}])

onMounted(()=>{
    XiaLa();
    GetOrder();
})
const XiaLa=()=>{
    // 获取商品数据
    axios.get("api/app/order-form/item")
    .then(res=>{ 
      Dm_Item.value=res.data.data;
      console.log(res.data.data);
    })


    // 获取供应商数据
    axios.get("api/app/order-form/ent")
    .then(res=>{ 
      Dm_Ent.value=res.data.data;
      console.log(res.data.data);
    })
}
const GetOrder=()=>{

    axios.get("api/app/order-form/order-form",{
        params:{
          pageindex: model.value.pageindex,
          pagesize: model.value.pagesize
        }
    })
    .then(res=>{ 
      OrderForm.value=res.data.pageData;
      model.value.totalCount=res.data.totalCount;
      model.value.totalPages=res.data.totalPages;
      console.log(res.data.pageData);
    })
}

// 格式化日期显示为年月日
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}


const cnm=reactive({
    isAdd: false,
    title:"",
    isopen:false
})

const open=(row:any)=>{
    if(row==null)
    {
        cnm.title="新增"
        cnm.isAdd=true
        cnm.isopen=true,
        form.orderFormId='',
        form.itemId='',
        form.itemNum=0,
        form.amount="",
        form.type=0,
        form.createTime='',
        form.entId='',
        form.userId='',
        form.remark=''

    }
    else
    {
        cnm.title="修改"
        cnm.isAdd=false
        cnm.isopen=true,
        updateform.id=row.id,
        form.orderFormId=row.orderFormId,
        form.itemId=row.itemId,
        form.itemNum=row.itemNum,
        form.amount=row.amount,
        form.type=row.type,
        form.createTime=row.createTime,
        form.entId=row.entid,
        form.userId=row.userId,
        form.remark=row.remark
        console.log(row);
         ElMessage.info(`修改订单：${row.orderFormId}`)
    }
   
    
}

const codeView = async () => {
    const response = await axios.post(
      "api/app/dm_Encoderule/start-code",{},
      {
        params: {
          Formtypeid: "订单单"
        }
      }
    );

    if (response.data && response.data.code === 200) {
      form.orderFormId = response.data.data;
    } else {
      ElMessage.error("订单编码失败");
    }
  
}

// 删除操作
const Del = async (id: any) => {
    ElMessageBox.confirm(
        '亲 ！您确定真的要删除吗？？？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    .then(() => {
        // 使用 axios.get 替代 axios.delete
        axios.get(`api/app/order-form/${id}/order-del`)
            .then(res => {
                if (res.data.code === 200) {
                    ElMessage.success(res.data.message);
                    GetOrder(); // 刷新数据
                } else {
                    ElMessage.error(res.data.message);
                }
            })
            .catch(error => {
                console.error("删除请求失败:", error);
                ElMessage.error("删除请求失败");
            });
    })
    .catch(() => {
        ElMessage({
            type: 'info',
            message: '取消成功',
        });
    });
}

// 提交表单
const handleSubmit = async () => {

  // 如果是新增操作
  if(cnm.isAdd==true)
  {
     await codeView();
      axios.post("api/app/order-form/order-form",form)
      .then(res=>{
          if(res.data.code==200)
          {
            ElMessage.success('保存成功');
            cnm.isopen=false;
            GetOrder();
          }
          else
          {
            ElMessage.error('保存失败');
          }
      })
  }
  else{
    const updateData={...form,id:updateform.id}
      axios.put("api/app/order-form/order-form",updateData)
      .then(res=>{
          if(res.data.code==200)
          {
            ElMessage.success('修改成功');
            cnm.isopen=false;
            GetOrder();
          }
          else
          {
            ElMessage.error('修改失败');
          }
      })
  }
}

// 重置表单
const handleReset = () => {
  form.orderFormId = ''
  form.itemId = ''
  form.itemNum = 0
  form.amount = ''
  form.type = 0
  form.createTime = ''
  form.entId = ''
  form.userId = ''
  form.remark = ''
}

// 分页处理函数
const handleSizeChange = (newSize: number) => {
  model.value.pagesize = newSize
  model.value.pageindex = 1 // 重置到第一页
  GetOrder()
}

const handleCurrentChange = (newPage: number) => {
  model.value.pageindex = newPage
  GetOrder()
}
</script>